#!/usr/bin/env python
import os
import subprocess
import pygtk
pygtk.require('2.0')
import gtk
import time
import threading
import gobject

gobject.threads_init()

class LogViewer(threading.Thread):

    mInFile = ""
    mTextBuffer = None
    mOldStrings = ""
    mStoped = False

    def close_application(self, widget):
        gtk.main_quit()
        self.mStoped = True

    def __init__(self, pathFile):
        threading.Thread.__init__(self)
        self.mInFile = pathFile
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_resizable(True)
        window.set_title(self.mInFile)
        window.set_border_width(10)
        window.set_default_size(800, 600)
        window.set_position(gtk.WIN_POS_CENTER_ALWAYS)
        window.connect("destroy", self.close_application)

        box1 = gtk.VBox(False, 10)
        window.add(box1)

        #box2 = gtk.VBox(False, 10)
        #box2.set_border_width(10)
        #box1.pack_start(box2, True, True, 0)
        #box2.show()

        sw = gtk.ScrolledWindow()
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        textview = gtk.TextView()
        textview.set_editable(False)
        textview.set_cursor_visible(False)
        textview.set_wrap_mode(gtk.WRAP_NONE)
        self.mTextBuffer = textview.get_buffer()
        sw.add(textview)
        sw.show()

        box1.pack_start(sw)
        #box2.pack_start(sw)

        textview.show()
        box1.show()
        window.show()

    def refreshFile(self):
        # Load the file into the text window
        infile = open(self.mInFile, "r")
        if infile:
            string = infile.read()
            infile.close()
            if cmp(string, self.mOldStrings) != 0:
                self.mTextBuffer.set_text(string)
            self.mOldStrings = string

    def run(self):
        while not self.mStoped:
            gobject.idle_add(self.refreshFile)
            time.sleep(1)

def main():
    subprocess.Popen('mkdir -p /tmp/logs', shell=True)
    # selected = os.environ.get('NAUTILUS_SCRIPT_SELECTED_URIS', '')
    selected = os.environ.get('NAUTILUS_SCRIPT_SELECTED_FILE_PATHS', '')
    curdir = os.environ.get('NAUTILUS_SCRIPT_CURRENT_URI', os.curdir)
    if selected:
        orig_targets = selected.splitlines()
    else:
        orig_targets = [curdir]

    converted = ""

    for target in orig_targets:
        if target.startswith('file:///'):
            target = target[7:]
        converted += (target + " ")

    foutput = "/tmp/logs/nautilus_fg3." + time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
    f = open(foutput, "w");
    # Using pygtk
    # p = subprocess.Popen("/home/finalx/mybin/myflash.sh --oneshot " + converted, shell=True, stdout=f)
    # app = LogViewer(foutput)
    # app.start()

    # Or using gnome-terminal
    subprocess.Popen('gnome-terminal -e "/home/finalx/mybin/myflash.sh ' + converted + '"', shell=True, stdout=f)

if __name__ == "__main__":
    main()
    #gtk.main()
